package com.hzlj.position.dbsync.jinan.listener;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fz.common.base.core.JsonUtils;
import com.fz.common.kafka.annotation.KafkaListenerDelay;
import com.fz.common.kafka.annotation.KafkaListenerRetry;
import com.hzlj.common.message.common.dto.message.MessageNoticeResultDTO;
import com.hzlj.common.message.common.util.MessageRestUtil;
import com.hzlj.position.config.common.dto.jzJbxxDeviceBind.JzJbxxDeviceBindMsgDTO;
import com.hzlj.position.config.common.dto.jzJbxxDeviceBind.JzJbxxDeviceBindQueryResultDTO;
import com.hzlj.position.config.common.enums.CRUDEnum;
import com.hzlj.position.config.common.enums.ChannelType;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.hzlj.position.config.common.constant.Topic.DEVICE_BIND;


/**
 * @author lifh
 * @date 2023/3/17 11:29
 **/
@Slf4j
@Component
public class JzJbxxDeviceBindListener {

    @KafkaListenerRetry(enable = false)
    @KafkaListenerDelay(delay = "5", delayUnit = TimeUnit.SECONDS)
    @KafkaListener(topics = {DEVICE_BIND})
    public void jzJbxxDeviceBind(ConsumerRecord<String, JzJbxxDeviceBindMsgDTO> record) {
        log.info("【kafka】收到设备同步消息:{}", record.value());
        JzJbxxDeviceBindMsgDTO bind = record.value();
        try {
            //同步App信息
            syncAppLocateInterval(record);
        } catch (Exception e) {
            log.info("【kafka】腕带同步信息:{}", bind, e);
        }
    }


    private void syncAppLocateInterval(ConsumerRecord<String, JzJbxxDeviceBindMsgDTO> record) {
        JzJbxxDeviceBindMsgDTO msg = record.value();
        JzJbxxDeviceBindQueryResultDTO bind = msg.getBind();
        //如果不是App
        if (!ChannelType.APP.getCode().equals(bind.getChannelType())
                || ObjectUtil.isEmpty(bind.getJzId())) {
            return;
        }

        switch (CRUDEnum.of(msg.getCrud())) {
            case ADD:
            case UPDATE:
            case UPDATE_DEVICE_CODE:
                MessageNoticeResultDTO noticeResult = MessageRestUtil.noticeQueryUsers(
                        "free-fill-websocket-jzry",
                        null,
                        MapUtil.<String, Object>builder("content", "{\"cmd\":\"updateLocateInterval\",\"locateInterval\":" + bind.getLocateInterval() + "}").build(),
                        false,
                        bind.getJzId()
                );
                if (noticeResult.isFail()) {
                    log.warn("设置定位间隔失败(app):jzId={},result={}", bind.getJzId(), JsonUtils.obj2json(noticeResult));
                }
                break;
            default:
                break;
        }
    }


}
